package drds.plus.sequence;

import lombok.Data;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 序列区间Sequence Range
 */
@Data
public class Range {
    private final long min;
    private final long max;
    private final AtomicLong value;
    private volatile boolean over = false;

    public Range(long min, long max) {
        this.min = min;
        this.max = max;
        this.value = new AtomicLong(min);
    }

    public long getAndIncrement() {
        long currentValue = value.getAndIncrement();
        if (currentValue > max) {
            over = true;
            return -1;
        }
        return currentValue;
    }

    public long getBatch(int size) {
        long currentValue = value.getAndAdd(size) + size - 1;
        if (currentValue > max) {
            over = true;
            return -1;
        }
        return currentValue;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("min: ").append(min).append(", max: ").append(max).append(", value: ").append(value);
        return sb.toString();
    }

}
